package com.youdoneed.community.common.jpush;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JiGuangService {

    private final Logger logger = LoggerFactory.getLogger(JiGuangService.class);

    private static final String COOLFACE_APP_KEY = "d491a817a0b20153221b66e6";

    private static final String COOLFACE_SECRET = "ed43ae385a9880b80691e32c";

    private static JPushClient CoolfaceJpushClient = null;


    /*
     * 保存离线的时长。秒为单位。最多支持10天（864000秒）。 
     * 0 表示该消息不保存离线。即：用户在线马上发出，当前不在线用户将不会收到此消息。 
     * 此参数不设置则表示默认，默认为保存1天的离线消息（86400秒 
     */
    private static long timeToLive = 60 * 60 * 24;
    
    /**
     * 推送消息到指定的app
     * @param id
     * @param title
     * @param msg
     * @param msgType(额外的类型)
     * @author lixs
     * @Date 2017.11.20
     */
    public boolean jpushForCoolface(String id, String title, String msg,String msgType){
    	if (CoolfaceJpushClient == null) {
    		CoolfaceJpushClient = new JPushClient(COOLFACE_SECRET, COOLFACE_APP_KEY);
//			MerchantJpushClient = new JPushClient(MERCHANT_MASTER_SECRET, MERCHANT_APP_KEY, null, ClientConfig.getInstance());
        }

        if (logger.isInfoEnabled()) {
            logger.info("调用jpush for merchant 开始发送消息:id=" + id + ",title=" + title + ",msg=" + msg+",msgType"+msgType);
        }

        // For push, all you need do is to build PushPayload object.
        PushPayload payload = buildPushObjectByregistrationId(id, msg, title,msgType);

        PushResult result = null;
        try {
            result = CoolfaceJpushClient.sendPush(payload);
            logger.info("Got result - " + result);

        } catch (APIConnectionException e) {
            // Connection error, should retry later
            logger.error("Connection error, should retry later", e);
            return false;
        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            logger.error("Should review the error, and fix the request", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
            return false;
        }

        System.out.println("发送极光消息结果 :" + result);
        return true;
    }
    
    /**
     * 才用别名推送信息
     * @param id
     * @param title
     * @param msg
     * @param msgType
     * @return
     */
    public boolean jpushForCoolfaceByAlias(String alias, String title, String msg,String msgType){
    	if (CoolfaceJpushClient == null) {
    		CoolfaceJpushClient = new JPushClient(COOLFACE_SECRET, COOLFACE_APP_KEY);
//			MerchantJpushClient = new JPushClient(MERCHANT_MASTER_SECRET, MERCHANT_APP_KEY, null, ClientConfig.getInstance());
        }

        if (logger.isInfoEnabled()) {
            logger.info("调用jpush for merchant 开始发送消息:alias=" + alias + ",title=" + title + ",msg=" + msg+",msgType"+msgType);
        }

        // For push, all you need do is to build PushPayload object.
        PushPayload payload = buildPushObjectByAlias(alias, msg, title,msgType);

        PushResult result = null;
        try {
            result = CoolfaceJpushClient.sendPush(payload);
            logger.info("Got result - " + result);

        } catch (APIConnectionException e) {
            // Connection error, should retry later
            logger.error("Connection error, should retry later", e);
            return false;
        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            logger.error("Should review the error, and fix the request", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
            return false;
        }

        System.out.println("发送极光消息结果 :" + result);
        return true;
    }

    
    public static PushPayload buildPushObjectByregistrationId(String id, String ALERT, String TITLE,String extrasparam) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
//                .setAudience(Audience.tag("tag1"))
                .setAudience(Audience.registrationId(id))
                .setNotification(Notification.newBuilder()
	            //指定当前推送的android通知
	            .addPlatformNotification(AndroidNotification.newBuilder()
	            	.setAlert(ALERT)   //设置通知内容（必填）
	                .setTitle(TITLE)	//设置通知标题（可选）
	                //此字段为透传字段，不会显示在通知栏。用户可以通过此字段来做一些定制需求，如特定的key传要指定跳转的页面（value）
	                .addExtra("extrasparam",extrasparam)
	                .build())
                .addPlatformNotification(IosNotification.newBuilder()
    	                //传一个IosAlert对象，指定apns title、title、subtitle等
    	                .setAlert(ALERT)
    	                //直接传alert
    	                //此项是指定此推送的badge（应用角标）自动加1
    	                //.incrBadge(1)
    	                //此字段的值default表示系统默认声音；传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒，
    	                // 如果系统没有此音频则以系统默认声音提醒；此字段如果传空字符串，iOS9及以上的系统是无声音提醒，以下的系统是默认声音
    	                .setSound("sound.caf")
    	                //此字段为透传字段，不会显示在通知栏。用户可以通过此字段来做一些定制需求，如特定的key传要指定跳转的页面（value）
    	                .addExtra("extrasparam", extrasparam)
    	                //此项说明此推送是一个background推送，想了解background看：http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
    	                //取消此注释，消息推送时ios将无法在锁屏情况接收
    	                // .setContentAvailable(true)
    	                .build())
                .build())
                .build();
    }
    

    /**
     * 通过别名来推送信息
     * @param aliases
     * @param ALERT
     * @param TITLE
     * @param extrasparam
     * @return
     */
    public static PushPayload buildPushObjectByAlias(String aliases, String ALERT, String TITLE,String extrasparam) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
//                .setAudience(Audience.tag("tag1"))
//                .setAudience(Audience.registrationId(id))
                .setAudience(Audience.alias(aliases))
                .setNotification(Notification.newBuilder()
	            //指定当前推送的android通知
	            .addPlatformNotification(AndroidNotification.newBuilder()
	            	.setAlert(ALERT)   //设置通知内容（必填）
	                .setTitle(TITLE)	//设置通知标题（可选）
	                //此字段为透传字段，不会显示在通知栏。用户可以通过此字段来做一些定制需求，如特定的key传要指定跳转的页面（value）
	                .addExtra("extrasparam",extrasparam)
	                .build())
                .addPlatformNotification(IosNotification.newBuilder()
    	                //传一个IosAlert对象，指定apns title、title、subtitle等
    	                .setAlert(ALERT)
    	                //直接传alert
    	                //此项是指定此推送的badge（应用角标）自动加1
    	                //.incrBadge(1)
    	                //此字段的值default表示系统默认声音；传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒，
    	                // 如果系统没有此音频则以系统默认声音提醒；此字段如果传空字符串，iOS9及以上的系统是无声音提醒，以下的系统是默认声音
    	                .setSound("sound.caf")
    	                //此字段为透传字段，不会显示在通知栏。用户可以通过此字段来做一些定制需求，如特定的key传要指定跳转的页面（value）
    	                .addExtra("extrasparam", extrasparam)
    	                //此项说明此推送是一个background推送，想了解background看：http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
    	                //取消此注释，消息推送时ios将无法在锁屏情况接收
    	                // .setContentAvailable(true)
    	                .build())
                .build())
                .build();
    }
    
	}

		

